import * as puppeteer from 'puppeteer'; // 引入Puppeteer
import * as cheerio from 'cheerio';
import axios from 'axios';
axios.defaults.headers.common['Authorization'] = 'APPCODE a18223c524674fd6a53347bef2e3bf52';

function Sleep(time:number):any{
    return new Promise(res => {
        setTimeout(()=>res(),time * 1000)
    })
}

class Crawler {
    public constructor() {
        this.smsapis = this.smsapis.bind(this)
    }

    async smsapis(sms: string) {

        try {
          
            console.log(sms,encodeURIComponent(sms))
            const data: any = await axios.get(`http://smsbanling.market.alicloudapi.com/smsapis?mobile=18612354779&msg=${encodeURIComponent(sms)}`);
            console.log(data.data);
            if (data.data.errmsg === 'OK') {
                console.log("短信发送成功")
            } else {
                console.log("短信发送失败",111);

                await Sleep(10);

                this.smsapis(sms);

            }

        } catch (e) {
            console.log("短信发送失败",e.toString());

            await Sleep(10);

            this.smsapis(sms);
        }

    }

    async start(URL: String) {
        // 通过Puppeteer启动一个浏览器环境
        const browser = await puppeteer.launch({ 
            args: ['--no-sandbox', '--disable-setuid-sandbox'],
            ignoreDefaultArgs: ['--disable-extensions'],
            headless:true
        });
        try {
            // 打开一个新的页面
            const page = await browser.newPage();
            page.setUserAgent('Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36');
            // 打开页面
            await page.goto(URL);
            console.log("页面打开完毕")

            const goldPriceHtml: Object = await page.$(".touziList.fs16");

            const goldPrice: String = await page.evaluate(dom => dom.innerHTML, goldPriceHtml);

            const HTML = cheerio.load(goldPrice)("ul li");


            const Price = `${HTML.eq(0).text()};${HTML.eq(1).text()}`
           
            await this.smsapis(Price);

            await browser.close();


        } catch (e) {
            console.log("错误", e.toString())

        }

    }
}

export default Crawler